﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Pavilion
{
    public class PolygonPhysicalData : PhysicalData
    {
        public PolygonBox PhysicalBounds { get; private set; }

        public PolygonPhysicalData() : base()
        {
            PhysicalBounds = new PolygonBox();
            PhysicalBounds.PointAdded += (point, index) => { if (IsFlippedHorizontally) InvertPoint(index); };
            PhysicalBounds.PolygonBoxChanged += (box) => OnPhysicalFormChanged();
            IsFlippedHorizontallyChanged += (x) => Invert();
        }

        public override void Move(float xDistance, float yDistance)
        {
            base.Move(xDistance, yDistance);

            if (xDistance == 0 && yDistance == 0)
                return;

            PhysicalBounds.BeginChanges();
            PhysicalBounds.TransformPoints(xDistance, yDistance);
            PhysicalBounds.EndChanges();
        }

        public void Invert()
        {
            PhysicalBounds.BeginChanges();

            for (int i = 0; i < PhysicalBounds.Count; i++)
                InvertPoint(i);

            PhysicalBounds.EndChanges();
        }

        private void InvertPoint(int index)
        {
            float invertXAmount = (Position.X - PhysicalBounds[index].X) * 2;
            PhysicalBounds[index] = new Vector2(PhysicalBounds[index].X + invertXAmount, PhysicalBounds[index].Y);
        }
    }
}
